﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NReader.Model;
using NReader.Model.RAS;
using NReader.Service;
using Windows.Data.Html;
using Windows.UI;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using XnReader.WinRT.Common;
using XnReader.WinRT.Controlx;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace XnReader.WinRT.Forms
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class ChapterIndex
    {
        /// <summary>
        /// 存储小说信息
        /// </summary>
        public static readonly ArticleInfo _article = new ArticleInfo();

        /// <summary>
        /// 存储当前章节信息,online
        /// </summary>
        public static ChapterInfo _chapter;

        /// <summary>
        /// 存储目标页面站点信息,online
        /// </summary>
        private static SysWebInfo _webInfo;

        /// <summary>
        /// 存储当前整书内容
        /// </summary>
        public static string _content;

        /// <summary>
        /// 指向当前一页结束位置处
        /// </summary>
        public static int _posEnd;

        /// <summary>
        /// 指向当前一页开始位置处
        /// </summary>
        public static int _posStart;

        /// <summary>
        /// 阅读设置
        /// </summary>
        private static SettingInfo _setting;

        /// <summary>
        /// 页面导航来源标记
        /// </summary>
        private string _lastflag;

        public ChapterIndex()
        {
            InitializeComponent();
            var visiblesTopBar = new CommandInfo
            {
                Theme = "white",
                VisibleNext = Visibility.Visible,
                VisiblePrevious = Visibility.Visible,
                VisibleGoBack = Visibility.Visible,
                VisibleList = Visibility.Visible,
            };
            if (header != null)
            {
                header.DataContext = visiblesTopBar;
                header.NextClickEvent += HeaderNextClickEvent;
                header.PreviousClickEvent += HeaderPreviousClickEvent;
                header.GoBackClickEvent += HeaderGoBackClickEvent;
                header.ListClickEvent += HeaderListClickEvent;
            }
            var visiblesBottomBar = new CommandInfo
            {
                Theme = "white",
                VisibleBackground = Visibility.Visible,
                VisibleFontSize = Visibility.Visible,
                VisibleFontFamily = Visibility.Visible
            };
            if (footer != null)
            {
                footer.DataContext = visiblesBottomBar;
                footer.BackgroundClickEvent += FooterBackgroundClickEvent;
                footer.FontFamilyClickEvent += FooterFontFamilyClickEvent;
                footer.FontSizeClickEvent += FooterFontSizeClickEvent;
            }
        }

        /// <summary>
        /// 书籍/书签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void HeaderListClickEvent(object sender, RoutedEventArgs e)
        {
            if(_article!=null)
            {
                if(_article.online.Equals(1))
                {
                    Frame.Navigate(typeof (BookReader), string.Format("{0}|{1}", _article.articleid, _chapter.chapterid));
                }
            }
        }

        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void HeaderGoBackClickEvent(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof (BookcaseDx));
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            //初次加载读取阅读设置
            if (_setting == null)
            {
                _setting = await GlobalService.Instance().GetSetting();
            }
            {
                DefaultViewModel["setting"] = _setting;
                sdFontSize.Value = _setting.FontSize;
            }
            var paramArr = navigationParameter.ToString().Split('|');
            if (paramArr.Length == 0)
                return;

            _lastflag = paramArr[0];
            //本地导入的书籍."跳转来源标记"+书籍ID+书名+文件后缀名+阅读进度
            if (_lastflag.Equals("offline"))
            {
                _article.online = 0;
                hlbLink.Visibility = Visibility.Collapsed;
                txtTips.Visibility = Visibility.Collapsed;
                await AnalyseOfflineContent(paramArr);
                await AnalyseOfflineView(paramArr);
            }
            else //online
            {
                _article.updatetime = DateTime.Now.ToString("yyyyMMddHHmmss");
                if (await AnslyseOnlineContent(paramArr))
                {
                    await AnalyseOnlineView(paramArr);
                    _article.historyprogress = (decimal) Math.Round((_posEnd*1.000000)/(_content.Length*1.000000), 9);
                    //更新阅读历史信息
                    await ArticleService.Instance().UpdateBook(_article);
                    txtHistoryProcess.Text = string.Format("{0}%", (_article.historyprogress*100) .ToString("N2"));
                    hlbLink.Visibility = Visibility.Visible;
                    txtTips.Visibility = Visibility.Visible;
                }
                else
                {
                    _article.historyprogress = 0;
                    //更新阅读历史信息
                    await ArticleService.Instance().UpdateBook(_article);
                    txtHistoryProcess.Text = string.Empty;
                    hlbLink.Visibility = Visibility.Collapsed;
                    txtTips.Text = "该页面由原网页直接提供";
                    //设置工具栏隐藏
                    BottomAppBar.Visibility = Visibility.Collapsed;
                }
            }
            pbLoading.IsActive = false;
        }

        /// <summary>
        /// 分析在线书籍内容
        /// </summary>
        /// <returns>返回true表示从缓存文件读取,false为直接链接到目标链接</returns>
        private async Task<bool> AnslyseOnlineContent(string[] paramArr)
        {
            var chapterid = int.Parse(paramArr[6]);
            var isReload = false;
            if (_chapter == null || !_chapter.chapterid.Equals(chapterid)) //新的章节
            {
                isReload = true;
                _posEnd = 0;
                _posStart = 0;

                //直接从WEB获取章节信息?san 后续修改为先从本地bookreader读取，没有再去下载
                _chapter = await ChapterService.GetChapterSession(int.Parse(paramArr[1]), chapterid);
                if (_chapter == null)
                {
                    _chapter = await ArticleService.Instance().GetChapter(chapterid);
                    await ChapterService.SaveChapterSession(_chapter);
                }
                _article.articleid = _chapter.articleid;
                _article.articlename = _chapter.articlename;
                _article.historyprogress = decimal.Parse(paramArr[4]);
                _article.historychapter = _chapter.chaptername;
                _article.historychapterid = _chapter.chapterid;
                _article.articletype = paramArr[3];
                _article.online = 1;
            }
            txtArticleName.Text = _chapter.articlename;
            txtHistoryChapter.Text = _chapter.chaptername;
            hlbLink.Visibility = Visibility.Visible;
            hlbLink.Tag = _chapter.chapterlink;
            //站点不允许匹配直接跳转
            if (_chapter.webstate.Equals(3))
            {
                _content = string.Empty;
                //未获取信息的直接跳转到源链接
                wvContent.Visibility = Visibility.Visible;
                rtxtView.Visibility = Visibility.Collapsed;
                wvContent.Navigate(new Uri(_chapter.chapterlink));
                return false;
            }
            if (isReload)
            {
                //await ChapterService.GetMaxChaptersLocal(_chapter.articleid);
                _webInfo = await GlobalService.Instance().GetSysWebInfoFromLocal(_chapter.webflag);
                //从本地获取内容
                _content = await ChapterService.GetChapterTxt(_chapter.webflag, _chapter.articleid, _chapter.chapterid);
                //var needSave = false;
                //var source = false;
                if (string.IsNullOrEmpty(_content))
                {
                    _content = await GetHtmlContent(); //从站点获取内容
                    if (!string.IsNullOrEmpty(_content))
                    {
                        //将文本保存本地
                        if (_chapter.ctype.Equals(0) && _chapter.webstate.Equals(1))//文本文件&&站点允许直接缓存
                        {
                            _content = MatchChapterContent(_content);
                            if (!string.IsNullOrEmpty(_content))
                            {
                                _content = HtmlUtilities.ConvertToText(_content);
                                await Task.Run(() => ChapterService.SaveChapterTxt(_chapter.webflag,
                                                                                   _chapter.articleid,
                                                                                   _chapter.chapterid,
                                                                                   _content));
                            }
                        }
                    }
                }
                if (string.IsNullOrEmpty(_content))
                {
                    //未获取信息的直接跳转到源链接
                    wvContent.Visibility = Visibility.Visible;
                    rtxtView.Visibility = Visibility.Collapsed;
                    wvContent.Navigate(new Uri(_chapter.chapterlink));
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 分析在线书籍显示
        /// </summary>
        /// <param name="paramArr"></param>
        /// <returns></returns>
        private async Task AnalyseOnlineView(string[] paramArr)
        {
            var text = "";
            pgrapView.Inlines.Clear();
            rtxtView.UpdateLayout();
            //如果是当前页，而且未阅读过，则需要显示下一页。否则阅读过，则要显示上一页
            var flag = "previous";
            if (paramArr[5].Equals("current")) //当前章节
            {
                _posStart = int.Parse(Math.Round(_content.Length * _article.historyprogress, 0).ToString());
                if ( _posStart == 0)//未阅读过
                {
                    flag = "next";
                }
            }
            else if (paramArr[5].Equals("next"))
            {
                flag = "next";
            }
            if (flag.Equals("next")) //下一章
            {
                _posStart = _posEnd; //开始游标指向页首
                for (; _posEnd < _content.Length; _posEnd++)
                {
                    text = string.Format("{0}{1}", text, _content[_posEnd]);
                    var paraContent = new Run { Text = text };
                    if (pgrapView.Inlines.Count > 0)
                        pgrapView.Inlines.RemoveAt(0);

                    pgrapView.Inlines.Add(paraContent);

                    rtxtView.UpdateLayout();
                    if (rtxtView.HasOverflowContent)
                    {
                        break;
                    }
                }
            }
            else
            {
                _posEnd = _posStart; //开始游标指向页尾
                for (; _posStart > 0; _posStart--)
                {
                    text = string.Format("{0}{1}", _content[_posStart-1], text);
                    var paraContent = new Run { Text = text };
                    if (pgrapView.Inlines.Count > 0)
                        pgrapView.Inlines.RemoveAt(0);

                    pgrapView.Inlines.Add(paraContent);

                    rtxtView.UpdateLayout();
                    if (rtxtView.HasOverflowContent)
                    {
                        break;
                    }
                }
            }

        }

        /// <summary>
        /// 分析获取离线文件内容
        /// </summary>
        /// <param name="paramArr"></param>
        /// <returns></returns>
        private async Task AnalyseOfflineContent(string[] paramArr)
        {
            #region 重新读取整个文件

            if (_article.articleid != int.Parse(paramArr[1]) && _article.articlename != paramArr[2])
            {
                _posEnd = 0;
                _posStart = 0;
                _article.articleid = int.Parse(paramArr[1]);
                _article.articlename = paramArr[2];
                _article.articletype = paramArr[3];
                var fileinfo = await
                               ArticleService.Instance().GetImportContent(string.Format("{0}{1}",
                                                                                                        _article.
                                                                                                            articlename,
                                                                                                        _article.
                                                                                                            articletype),
                                                                                          (double)
                                                                                          _article.historyprogress,//已作废
                                                                                          1024 * 2,
                                                                                          "gb2312");
                if (fileinfo != null)
                    _content = fileinfo.Content.Trim();
            }
            txtArticleName.Text = _article.articlename;
            txtHistoryChapter.Text = _article.historychapter ?? "";
            #endregion
        }

        /// <summary>
        /// 分析离线文件显示
        /// </summary>
        /// <returns></returns>
        private async Task AnalyseOfflineView(string[] paramArr)
        {
            txtHistoryChapter.Visibility = Visibility.Collapsed;

            #region 翻页

            _article.historyprogress = decimal.Parse(paramArr[4]);
            var text = "";
            pgrapView.Inlines.Clear();
            rtxtView.UpdateLayout();
            var flag = "previous";
            if (paramArr[5].Equals("current")) //当前章节
            {
                _posStart = int.Parse(Math.Round(_content.Length * _article.historyprogress, 0).ToString());
                if (_posStart == 0)//未阅读过
                {
                    flag = "next";
                }
            }
            else if (paramArr[5].Equals("next"))
            {
                flag = "next";
            }
            if (flag.Equals("next")) //下一章
            {
                _posStart = _posEnd; //开始游标指向页首
                for (; _posEnd < _content.Length; _posEnd++)
                {
                    text = string.Format("{0}{1}", text, _content[_posEnd]);
                    var paraContent = new Run {Text = text};
                    if (pgrapView.Inlines.Count > 0)
                        pgrapView.Inlines.RemoveAt(0);

                    pgrapView.Inlines.Add(paraContent);

                    rtxtView.UpdateLayout();
                    if (rtxtView.HasOverflowContent)
                    {
                        break;
                    }
                }
            }
            else
            {
                _posEnd = _posStart; //开始游标指向页尾
                for (; _posStart > 0; _posStart--)
                {
                    text = string.Format("{0}{1}", _content[_posStart-1], text);
                    var paraContent = new Run {Text = text};
                    if (pgrapView.Inlines.Count > 0)
                        pgrapView.Inlines.RemoveAt(0);

                    pgrapView.Inlines.Add(paraContent);

                    rtxtView.UpdateLayout();
                    if (rtxtView.HasOverflowContent)
                    {
                        break;
                    }
                }
            }
            #endregion
            _article.updatetime = DateTime.Now.ToString("yyyyMMddHHmmss");
            _article.historyprogress = (decimal) Math.Round((_posEnd*1.000000)/(_content.Length*1.000000), 9);
            //更新阅读历史信息
            await ArticleService.Instance().UpdateBook(_article);
            txtHistoryProcess.Text = string.Format("{0}%", (_article.historyprogress*100).ToString("N2"));
            #region
            //?san 由于暂时没解决绑定2个数据源，修改为直接给控件赋值
            //this.DefaultViewModel["article"] = _article;
            #endregion
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {

        }

        /// <summary>
        /// 点击文本翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RtxtViewPointerPressed(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
        {
            var pt = e.GetCurrentPoint(sender as FrameworkElement);
            if (pt.Properties.PointerUpdateKind != PointerUpdateKind.RightButtonPressed)
            {
                var hits = pt.Position;
                bool isNext = hits.X > Window.Current.Bounds.Width/2;
                if(isNext)
                {
                    HeaderNextClickEvent(null, null);
                }
                else
                {
                    HeaderPreviousClickEvent(null, null);
                }
                //double historyprogress = Math.Round((_posEnd*1.000000)/(_content.Length*1.000000), 9);
                //var flag = _article.online.Equals(1) ? "online" : "offline";
                //if (isNext)
                //{
                //    if (_posEnd.Equals(_content.Length)) return; //最后一页
                //    var param = string.Format("{0}|{1}|{2}|{3}|{4}|next|{5}", flag,
                //                              _article.articleid,
                //                              _article.articlename,
                //                              _article.articletype,
                //                              (decimal) historyprogress, _article.historychapterid.Equals(0)
                //                                                             ? _article.lastchapterid
                //                                                             : _article.historychapterid);
                //    Frame.Navigate(typeof (ChapterIndex), param);
                //}
                //else
                //{
                //    if (_posStart == 0) return; //第一页
                //    var param = string.Format("{0}|{1}|{2}|{3}|{4}|previous|{5}", flag,
                //                              _article.articleid,
                //                              _article.articlename,
                //                              _article.articletype,
                //                              (decimal) historyprogress, _article.historychapterid.Equals(0)
                //                                                             ? _article.lastchapterid
                //                                                             : _article.historychapterid);
                //    Frame.Navigate(typeof (ChapterIndex), param);
                //}
                #region

                ////通过检测溢出获取起止位置
                //var paragraph = rtxtView.Blocks[0] as Paragraph;
                //var run = paragraph.Inlines[paragraph.Inlines.Count - 1] as Run;
                //var str = run.Text.Substring(rtxtView.ContentEnd.Offset-1);

                #endregion
            }
        }

        /// <summary>
        /// 上一章
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void HeaderPreviousClickEvent(object sender, RoutedEventArgs e)
        {
            if (_article == null) return;
            var flag = _article.online.Equals(1) ? "online" : "offline";
            if(flag.Equals("offline"))
            {
                NavPrevPage(flag,0);
            }
            else
            {
                //在线且以文本显示
                if (BottomAppBar.Visibility == Visibility.Visible)
                {
                    //当前章节的第一部分
                    if (_posStart.Equals(0))
                    {
                        NavPrevChapterOnline();
                    }
                    else
                    {
                        NavPrevPage(flag, _article.historychapterid);
                    }
                }
                else
                {
                    NavPrevChapterOnline();
                }
            }
            //double historyprogress = Math.Round((_posEnd*1.000000)/(_content.Length*1.000000), 9);
            //var flag = _article.online.Equals(1) ? "online" : "offline";

            //if (_posStart == 0) return; //第一页
            //var param = string.Format("{0}|{1}|{2}|{3}|{4}|previous|{5}", flag,
            //                          _article.articleid,
            //                          _article.articlename,
            //                          _article.articletype,
            //                          (decimal) historyprogress, _article.historychapterid.Equals(0)
            //                                                         ? _article.lastchapterid
            //                                                         : _article.historychapterid);
            //Frame.Navigate(typeof (ChapterIndex), param);
        }

        /// <summary>
        /// 下一章
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void HeaderNextClickEvent(object sender, RoutedEventArgs e)
        {
            if (_article == null) return;
            var flag = _article.online.Equals(1) ? "online" : "offline";
            //离线进度跳转
            if (flag.Equals("offline"))
            {
                NavNextPage(flag,0);
            }
            else
            {
                //在线且以文本显示
                if (BottomAppBar.Visibility == Visibility.Visible)
                {
                    //当前章节的最后一部分
                    if (_posEnd.Equals(_content.Length))
                    {
                        NavNextChapterOnline();
                    }
                    else
                    {
                        NavNextPage(flag,_article.historychapterid);
                    }
                }
                else
                {
                    NavNextChapterOnline();
                }
            }
        }
       
        /// <summary>
        /// 导航到上一页面
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="chapterid">下一章节ID/历史阅读的章节ID</param>
        private void NavPrevPage(string flag, int chapterid)
        {
            double historyprogress = Math.Round((_posEnd * 1.000000) / (_content.Length * 1.000000), 9);
            if (_posStart == 0) return; //第一页
            var param = string.Format("{0}|{1}|{2}|{3}|{4}|previous|{5}", flag,
                                      _article.articleid,
                                      _article.articlename,
                                      _article.articletype,
                                      (decimal)historyprogress,
                                      chapterid);
                                      //(decimal)historyprogress, _article.historychapterid.Equals(0)
                                      //                               ? _article.lastchapterid
                                      //                               : _article.historychapterid);
            Frame.Navigate(typeof(ChapterIndex), param);
        }
                
        /// <summary>
        /// 导航到在线的上一章节
        /// </summary>
        private void NavPrevChapterOnline()
        {
            if (_chapter.previewpage>0)
            {
                var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                                          _article.articleid,
                                          _article.articlename,
                                          _article.articletype,
                                          0, //_article.historyprogress,
                                          _chapter.previewpage);
                Frame.Navigate(typeof (ChapterIndex), param);
            }
        }
    
        /// <summary>
        /// 导航到下一部分
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="chapterid"></param>
        private void NavNextPage(string flag, int chapterid)
        {
            if (_posEnd.Equals(_content.Length)) return; //最后一页
            double historyprogress = Math.Round((_posEnd*1.000000)/(_content.Length*1.000000), 9);
            var param = string.Format("{0}|{1}|{2}|{3}|{4}|next|{5}", flag,
                                      _article.articleid,
                                      _article.articlename,
                                      _article.articletype,
                                      (decimal)historyprogress,
                                      chapterid);
            Frame.Navigate(typeof (ChapterIndex), param);
        }

        /// <summary>
        /// 导航到在线的下一章节
        /// </summary>
        private void NavNextChapterOnline()
        {
            if (_chapter.nextpage > 0)
            {
                var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                                          _article.articleid,
                                          _article.articlename,
                                          _article.articletype,
                                          0, //_article.historyprogress,
                                          _chapter.nextpage);
                Frame.Navigate(typeof (ChapterIndex), param);
            }
        }

        #region 设置背景

        void FooterBackgroundClickEvent(object sender, RoutedEventArgs e)
        {
            popBackground.VerticalOffset = Window.Current.Bounds.Height - 140;
            popBackground.HorizontalOffset = Window.Current.Bounds.Width - 240;
            popBackground.IsOpen = true;
        }

        private void ListViewItemClick(object sender, ItemClickEventArgs e)
        {
            if (_setting != null)
            {
                var val = e.ClickedItem as Image;
                if (val != null && val.Tag != null)
                {
                    _setting.Background = int.Parse(val.Tag.ToString());
                    //深色背景字体颜色为白色
                    if (_setting.Background.Equals(1) ||
                        _setting.Background.Equals(2) ||
                        _setting.Background.Equals(4))
                    {
                        _setting.FontColor = "white";
                        pgrapView.Foreground = new SolidColorBrush(Colors.White);
                    }
                    else
                    {
                        _setting.FontColor = "black";
                        pgrapView.Foreground = new SolidColorBrush(Colors.Black);
                    }
                    ibBackground.ImageSource =
                        new BitmapImage(
                            new Uri(string.Format("ms-appx:///Assets/theme/view{0}.jpg", _setting.Background)));
                }
            }
        }

        /// <summary>
        /// 关闭时将设置保存到文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PopSettingClosed(object sender, object e)
        {
            await GlobalService.Instance().SaveSetting(_setting);
        }

        #endregion

        #region 设置字体

        void FooterFontFamilyClickEvent(object sender, RoutedEventArgs e)
        {
            //bottombar高度+pop高度
            popFontFamily.VerticalOffset = Window.Current.Bounds.Height - 290;
            popFontFamily.HorizontalOffset = Window.Current.Bounds.Width - 120;
            popFontFamily.IsOpen = true;
        }

        private void LvFontFamilyItemClick(object sender, ItemClickEventArgs e)
        {
            if (_setting != null)
            {
                var val = e.ClickedItem as TextBlock;
                if (val != null && val.Tag != null)
                {
                    _setting.FontFamily = val.Tag.ToString();
                    pgrapView.FontFamily = new FontFamily(_setting.FontFamily);
                }
            }
        }
        
        #endregion

        #region 设置字体大小

        void FooterFontSizeClickEvent(object sender, RoutedEventArgs e)
        {
            popFontSize.VerticalOffset = Window.Current.Bounds.Height - 150;
            popFontSize.HorizontalOffset = Window.Current.Bounds.Width - 240;
            popFontSize.IsOpen = true;
        }

        private void SdFontSizeValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
        {
            if (sdFontSize != null && _setting != null)
            {
                _setting.FontSize = sdFontSize.Value;
            }
        }

        #endregion

        #region 设置编码

        //void FooterEncodingClickEvent(object sender, RoutedEventArgs e)
        //{
        //    //bottombar高度+pop高度
        //    popEncoding.VerticalOffset = Window.Current.Bounds.Height - 290;
        //    popEncoding.HorizontalOffset = Window.Current.Bounds.Width - 120;
        //    popEncoding.IsOpen = true;
        //}

        //private async void LvEncodingItemClick(object sender, ItemClickEventArgs e)
        //{
        //    if (_setting != null)
        //    {
        //        var val = e.ClickedItem as TextBlock;
        //        if (val != null && val.Tag != null)
        //        {
        //            _setting.Encoding = val.Tag.ToString();
        //            var param = string.Format("{0}|{1}|{2}|{3}|{4}|current", "history",
        //                                          _article.articleid,
        //                                          _article.articlename,
        //                                          _article.articletype,
        //                                          _article.historyprogress);
        //            Frame.Navigate(typeof(ChapterIndex), param);
        //        }
        //    }
        //}

        #endregion

        #region Http get html

        private HttpClient _httpClient;

        private async Task<string> GetHtmlContent()
        {
            if (_httpClient == null)
            {
                _httpClient = new HttpClient();
                //_httpClient.MaxResponseContentBufferSize = 25600;
                _httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            }
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(_chapter.chapterlink);
                response.EnsureSuccessStatusCode();
                var bytes = await response.Content.ReadAsByteArrayAsync();
                return Encoding.GetEncoding(_webInfo.encoding).GetString(bytes, 0, bytes.Length);
            }
            catch (HttpRequestException ex)
            {
                return string.Empty;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        private string MatchChapterContent(string html)
        {
            var match = Regex.Match(html, _webInfo.matchtext, RegexOptions.None);

            if (string.IsNullOrEmpty(match.Groups[1].Value)) return string.Empty;

            var result = match.Groups[1].Value;
            if (!string.IsNullOrEmpty(_webInfo.filtertext))
            {
                //[过滤方法：正则0，替换1]$[目标值/正则表达式]♂
                var arrs = _webInfo.filtertext.Split('♂');
                foreach (var arr in arrs)
                {
                    var splits = arr.Split('$');
                    if (splits.Count() >= 2)
                    {
                        result = splits[0].Equals("1") ? result.Replace(splits[1], string.Empty) : Regex.Replace(result, splits[1], string.Empty);
                    }
                }
            }
            return result;
        }

        private bool HasImages(string html)
        {
            var matchResult = Regex.Matches(html, _webInfo.matchimage, RegexOptions.None);
            return matchResult.Count > 0;
        }

        public static string ReplaceLinkText(string text)//过滤html,js,css代码
        {
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            //text = Regex.Replace(text, "<head[^>]*>(?:.|[\r\n])*?</head>", "");
            text = Regex.Replace(text, "<script[^>]*>(?:.|[\r\n])*?</script>", "");
            //////text = Regex.Replace(text, "<style[^>]*>(?:.|[\r\n])*?</style>", "");
            text = Regex.Replace(text, "<a\\s+[^>]*href=['\"][^'\">]*['\"][^>]*>", string.Empty, RegexOptions.IgnoreCase); //<a ></a>
            //text = Regex.Replace(text, "[\\s]{2,}", " "); //两个或多个空格替换为一个
            //text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", ""); //<br> 
            //text = Regex.Replace(text, "\\&[a-zA-Z]{1,10};", "");
            //text = Regex.Replace(text, "<[^>]*>", "");

            ////text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", ""); //&nbsp;
            ////text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //其它任何标记
            //text = text.Replace("'", "''");
            //text = text.Replace("\r\n", "");
            //text = text.Replace("  ", "");
            //text = text.Replace("\t", "");
            return text;
        }

        #endregion

        /// <summary>
        /// 点击原文链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void HlbLinkClick(object sender, RoutedEventArgs e)
        {
            await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
        }
    }
}
